<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="btn-add">
        <el-button
        icon="el-icon-circle-plus-outline"
        type="button"
        class="el-button el-button--primary"
        @click="showAdd = true"
        >
            新增</el-button
        >
    </div>

    <!-- 新增数据弹窗 -->
    <el-dialog
      title="新增"
      :visible.sync="showAdd"
      @close="showAdd = false"
      width="35%"
    >
        <el-form :model="createForm" ref="createForm" :rules="addRules" label-width="80px">
            <el-form-item label="产品编码" prop="facilityTechnologyNo" >
                <el-input v-model="createForm.facilityTechnologyNo" class="ul-item" @blur="getProcessListAdd(createForm.facilityTechnologyNo)"/>
            </el-form-item>
            <el-form-item label="使用工序" prop="facilityProcess" >
                <el-cascader :props="props" v-model="createForm.facilityProcess" :options="optionsprocess" clearable class="ul-item"/>
            </el-form-item>
            <el-form-item label="资源大类" prop="facilityBarcodeType1">
                <el-select
                filterable
                    v-model="createForm.facilityBarcodeType1"
                    class="ul-item"
                    @focus="getBarcodeType('大类')">
                    <el-option
                        v-for="(item,index) in barcodeType1List"
                        :key="index"
                        :label="item.facilityBarcodeChineseName+'-'+item.facilityBarcodeName"
                        :value="item.facilityBarcodeName">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="资源小类" prop="facilityBarcodeType2">
                <el-select
                filterable
                    v-model="createForm.facilityBarcodeType2"
                    class="ul-item"
                    @focus="getBarcodeType('小类')">
                    <el-option
                        v-for="(item,index) in barcodeType2List"
                        :key="index"
                        :label="item.facilityBarcodeChineseName+'-'+item.facilityBarcodeName"
                        :value="item.facilityBarcodeName">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="资源规格" prop="facilityBarcodeType3">
                <el-select
                filterable
                    v-model="createForm.facilityBarcodeType3"
                    class="ul-item"
                    @focus="getBarcodeType('规格')">
                    <el-option
                        v-for="(item,index) in barcodeType3List"
                        :key="index"
                        :label="item.facilityBarcodeChineseName+' / '+item.facilityBarcodeName+' / '+item.workCenter"
                        :value="item.facilityBarcodeName">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-link type="warning" :underline="false">备注：资源信息筛选 中文名称--编码--工作中心</el-link>
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showAdd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="addfacility('createForm')"
            >新增</el-button
            >
        </div>
    </el-dialog>


    <div class="filter-container">
      <!-- style="width: 150px;margin-right:15px;" -->
        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px"
            :style="{ width: inputWid(param.facilityTechnologyNo) }"
            v-model="param.facilityTechnologyNo"
            placeholder="产品编码"
        ></el-input>

        <!-- <el-input
            @keyup.enter.native="getData"
            clearable
            style="width: 150px;margin-right:15px;"
            v-model="param.facilityProcess"
            placeholder="使用工序"
        ></el-input> -->

        <el-button type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
        >
        重置</el-button>

    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="产品编码"  prop="facilityTechnologyNo" align="center"/>
      <el-table-column label="使用工序"  prop="facilityProcess" align="center"/>
      <el-table-column label="大类"  prop="facilityBarcodeType1" align="center"/>
      <el-table-column label="小类"  prop="facilityBarcodeType2" align="center"/>
      <el-table-column label="资源规格"  prop="facilityBarcodeType3" align="center"/>
      <!-- <el-table-column label="工作中心"  prop="workCenter" align="center"/> -->
      <el-table-column label="配置人员"  prop="userName" align="center"/>
      <el-table-column label="修改时间"  prop="updateTime" align="center"/>
      <el-table-column label="操作" fixed="right" align="center" width="160" v-if="userInfo.roleId == 0 || userInfo.roleId == 7 || userInfo.roleId == 14 || userInfo.roleId == 27 || userInfo.roleId == 9 || userInfo.roleId == 36">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                    <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button
                        icon="el-icon-delete"
                        class="el-button el-button--danger"
                        style="font-size: 15px;"
                        @click="handleDelete(scope.row,scope.$index)"
                    ></el-button>
                </div>
            </template>
      </el-table-column>
    </el-table>

    <!-- 修改数据弹窗 -->
    <el-dialog
      title="修改工序信息"
      :visible.sync="showupd"
      @close="showupd = false"
      width="35%"
    >
        <el-form :model="updForm" ref="updForm" :rules="addRules" label-width="80px">
            <el-form-item label="产品编码" prop="facilityTechnologyNo" >
                <el-input disabled v-model="updForm.facilityTechnologyNo" class="ul-item" @blur="getProcessList(updForm.facilityTechnologyNo)"/>
            </el-form-item>
            <el-form-item label="使用工序" prop="facilityProcess" >
                <!-- <el-cascader collapse-tags :props="props" v-model="updForm.facilityProcess" :options="optionsprocess" clearable class="ul-item"/> -->
                <el-select v-model="updForm.facilityProcess" class="ul-item" filterable  clearable>
                    <el-option v-for="(item,index) in optionsprocess" :key="index" :label="item.label" :value="item.label"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="资源大类" prop="facilityBarcodeType1">
                <el-select
                    v-model="updForm.facilityBarcodeType1"
                    class="ul-item"
                    filterable
                    clearable
                    disabled
                    @focus="getBarcodeType('大类')">
                    <el-option
                        v-for="(item,index) in barcodeType1List"
                        :key="index"
                        :label="item.facilityBarcodeChineseName"
                        :value="item.facilityBarcodeName">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="资源小类" prop="facilityBarcodeType2">
                <el-select
                    v-model="updForm.facilityBarcodeType2"
                    class="ul-item"
                    filterable
                    clearable
                    disabled
                    @focus="getBarcodeType('小类')">
                    <el-option
                        v-for="(item,index) in barcodeType2List"
                        :key="index"
                        :label="item.facilityBarcodeChineseName"
                        :value="item.facilityBarcodeName">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="资源规格" prop="facilityBarcodeType3">
                <el-select
                    disabled
                    v-model="updForm.facilityBarcodeType3"
                    class="ul-item"
                    filterable
                    clearable
                    @focus="getBarcodeType('规格')">
                    <el-option
                        v-for="(item,index) in barcodeType3List"
                        :key="index"
                        :label="item.facilityBarcodeChineseName"
                        :value="item.facilityBarcodeName">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showupd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="updprocess('updForm')"
            >修改</el-button
            >
        </div>
    </el-dialog>

   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

  </div>
</template>

<script>
import { selprocessorder,addprocessorder,updprocessorder,delprocessorder,getProcessList,selbarcodeType } from "@/api/processRoute"
import { getCenter } from '../../api/workSection.js'
export default {
    name: 'frockconfigure',
    data () {
        return {
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                facilityTechnologyNo: '',                      //产品编码
                facilityProcess: '',                           //使用工序
            },
            total: 0,                                      //数据的总数
            tableInfo: [],
            loadingList: false,
            loading: false,
            centerList: [],                         //工作中心列表
            createForm: {},
            updForm: {},
            props: { multiple: true },
            optionsprocess: [],
            // 表单校验
            addRules: {
                facilityTechnologyNo: [
                    { required: true, message: "产品编码不能为空!", trigger: "change" },
                ],
                facilityProcess: [
                    { required: true, message: "使用工序不能为空!", trigger: "change" },
                ],
                facilityBarcodeType1: [
                    { required: true, message: "资源大类不能为空!", trigger: "change" },
                ],
                facilityBarcodeType2: [
                    { required: true, message: "资源小类不能为空!", trigger: "change" },
                ],
                facilityBarcodeType3: [
                    { required: true, message: "资源规格不能为空!", trigger: "change" },
                ],
            },
            showAdd: false,
            showupd: false,
            userInfo: this.$store.state.user.userInfo,
            barcodeType1List: [],
            barcodeType2List: [],
            barcodeType3List: [],
            facilityProcess: ''
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        getData(){
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.listQuery)
            if(this.param.facilityTechnologyNo){ query.facilityTechnologyNo = this.param.facilityTechnologyNo}
            if(this.param.facilityProcess){ query.facilityProcess = this.param.facilityProcess}
            let data = await selprocessorder(query)
            let errmsg = data.msg
            this.loadingList = false
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            this.total = data.data.count
            this.tableInfo = data.data.list
        },
        // 新增  获取工序，需要转格式
        async getProcessListAdd(technologyNo){
            this.optionsprocess = []
            this.updForm.facilityProcess = ''
            this.createForm.facilityProcess = ''
            if(!technologyNo) return
            let data = await getProcessList({technologyNo: technologyNo,technologyEnd: technologyNo,page:1,limit:1000})
            let errmsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            data.data.records.forEach(item=>{
                let obj = {}
                obj.value = item.processOrder
                obj.label = item.processOrder
                obj.children = [{value:item.processName,label:item.processName}]
                this.optionsprocess.push(obj)
            })
        },
        async getProcessList(technologyNo){
            this.optionsprocess = []
            this.updForm.facilityProcess = ''
            this.createForm.facilityProcess = ''
            if(!technologyNo) return
            let data = await getProcessList({technologyNo: technologyNo,technologyEnd: technologyNo,page:1,limit:1000})
            let errmsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            data.data.records.forEach(item=>{
                let obj = {}
                obj.value = item.processOrder
                obj.label = item.processOrder
                this.optionsprocess.push(obj)
            })
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = {
            index: '序号',
            facilityTechnologyNo: '产品编码',
            facilityBarcodeType1: '资源大类',
            facilityBarcodeType2: '资源小类',
            facilityBarcodeType3: '资源规格',
            facilityProcess: '使用工序'
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1
          query.limit = 10000
          if(this.param.facilityTechnologyNo){ query.facilityTechnologyNo = this.param.facilityTechnologyNo}
          if(this.param.facilityProcess){ query.facilityProcess = this.param.facilityProcess}
          let arr = await selprocessorder(query)
          if(arr.code == '500') return
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          if(!arr.data.list.length) return this.$message.error('暂无数据')
          const { header, data } = this.transformDat(this.setSort(arr.data.list))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '工装工序配置excel', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              index: index+1,
              facilityTechnologyNo: item.facilityTechnologyNo,
              facilityBarcodeType1: item.facilityBarcodeType1,
              facilityBarcodeType2: item.facilityBarcodeType2,
              facilityBarcodeType3: item.facilityBarcodeType3,
              facilityProcess: item.facilityProcess
            }
            arr1.push(obj)
          })
          return arr1
        },
        cancelSubmit(){
            this.param = {
                facilityTechnologyNo: '',                      //产品编码
                facilityProcess: '',                                //使用工序
            }
            this.listQuery.page = 1
            this.handleFilter()
        },
        // 提交表单之前先进行验证
        addfacility(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitprocess()
                } else {
                    return false
                }
            })
        },
        async submitprocess(){
            let query = Object.assign({},this.createForm)
            if(!this.createForm.remark) { query.remark = ''}
            console.log(this.createForm.facilityProcess)
            for(let i = 0; i < this.createForm.facilityProcess.length; i++){
                query.facilityProcess = this.createForm.facilityProcess[i][0]
                const data = await addprocessorder(query)
                const errMsg = data.msg
                if(data.code == '500') return
                if(data.code != '1') return this.$message.error(errMsg)
                this.$message.success(errMsg)
            }
                this.resetForm()
                this.showAdd = false
                this.handleFilter()
        },
        resetForm(){
             this.$refs.createForm.resetFields();
        },
        handleEdit(row){
            this.getProcessList(row.facilityTechnologyNo)
            this.updForm = Object.assign({},row)
            this.facilityProcess = row.facilityProcess
            // this.updForm.facilityProcess = row.facilityProcess.split(',')
            this.showupd = true
        },
        // 提交表单之前先进行验证
        updprocess(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.updprocessorder()
                } else {
                    return false
                }
            })
        },
        async updprocessorder(){
            // let query = Object.assign({},this.updForm)
            // console.log(query)   
            // query.facilityProcess1 = this.updForm.facilityProcess
            // query.facilityProcess = this.facilityProcess
            const query = {
                facilityBarcodeType1:this.updForm.facilityBarcodeType1,
                facilityBarcodeType2:this.updForm.facilityBarcodeType2,
                facilityBarcodeType3:this.updForm.facilityBarcodeType3,
                facilityProcess:this.facilityProcess,
                facilityProcess1:this.updForm.facilityProcess,
                facilityTechnologyNo:this.updForm.facilityTechnologyNo,
                type:this.updForm.type,
                userName:this.updForm.userName,
            }
            const data = await updprocessorder(query)
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.showupd = false
            this.handleFilter()
            this.$message.success(errMsg)
        },
        // 获取工作中心
        async getCenterList() {
          let {data} = await getCenter()
          this.centerList = data
        },
        handleDelete(row,index) {
            this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delprocess(row,index)
            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                })
            })
        },  
        async delprocess(row,index){
          let query = {
            facilityTechnologyNo: row.facilityTechnologyNo,
            facilityProcess: row.facilityProcess,
            facilityBarcodeType1: row.facilityBarcodeType1,
            facilityBarcodeType2: row.facilityBarcodeType2,
            facilityBarcodeType3: row.facilityBarcodeType3,
          }
          let res = await delprocessorder(query)
          if(res.code == '500') return
          if(res.code != '1') return this.$message.error(res.msg)
          this.tableInfo.splice(index,1)
          this.$message.success(res.msg)
        },
        async getBarcodeType(type) {
            this.loadingList = true
            let query = {
                facilityBarcodeType: type,
                page: 1,
                limit: 10000
            }
            let data = await selbarcodeType(query)
            let errmsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            if(type == '大类'){
                this.barcodeType1List = data.data.records
            } else if(type == '小类') {
                this.barcodeType2List = data.data.records
            } else if(type == '规格') {
                this.barcodeType3List = data.data.records
            }
            this.loadingList = false
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>

.btn-add{
    margin-bottom: 28px;
}

.ul-item{
  width: 85%;
}
</style>
